package com.ls.que116_120;

import com.ls.day2.ListNode;

import java.util.ArrayList;

/**
 * @author ：ls
 * @date ：2022/3/31 20:44
 * @description：...
 */
public class Connect {
    public Node connect(Node root) {
        if (root==null)
            return root;
        ArrayList<Node> now = new ArrayList<>();
        ArrayList<Node> temp = new ArrayList<>();
        now.add(root);
        while (now.size()!=0){
            temp.clear();
            for (int i=0; i<now.size()-1;i++){
                now.get(i).next = now.get(i+1);

                if (now.get(i).left!=null) {
                    temp.add(now.get(i).left);
                }

                if (now.get(i).right!=null) {
                    temp.add(now.get(i).right);
                }
            }

            if (now.get(now.size()-1).left!=null){
                temp.add(now.get(now.size()-1).left);
            }
            if (now.get(now.size()-1).right!=null){
                temp.add(now.get(now.size()-1).right);
            }

            now.clear();
            now.addAll(temp);
        }
        return root;
    }
}
